package lib

import (
	"RMS/app/shop/model"
	"RMS/common"
	"RMS/common/db"
	"context"
	jsoniter "github.com/json-iterator/go"
	"gorm.io/gorm"
	"log"
)

func ImplBaobiaoQuery(ctx context.Context, req *model.BaobiaoReq) *model.BaobiaoResp {
	resp := &model.BaobiaoResp{}

	d := db.NewRmsDBRequest(ctx)
	d = d.Table(db.PmsOrderTable)

	if req.StartTime != nil && req.EndTime != nil {
		d.Where("event_time between ? and ?", *req.StartTime, *req.EndTime)
	}
	var data []map[string]interface{}
	if err := d.Find(&data).Error; err != nil && err != gorm.ErrRecordNotFound {
		log.Printf("ImplOrderList err := %v\n", err.Error())
		resp.Status = common.ErrCode
		resp.Message = common.FindErrMessage
		return resp
	}
	var count int64
	var total float64
	for i := 0; i < len(data); i++ {
		str, _ := data[i]["detail"].(string)
		temp := make(map[string]interface{})
		jsoniter.Unmarshal([]byte(str), &temp)
		for _, v := range temp {
			vstr, _ := v.(string)
			good := make(map[string]interface{})
			jsoniter.Unmarshal([]byte(vstr), &good)
			ty, _ := good["type"].(string)
			if req.Type != nil {
				if *req.Type == 0 && ty != "item" {
					continue
				} else if *req.Type == 1 && ty != "package" {
					continue
				}
				var name string
				if *req.Type == 0 {
					name, _ = good["category_name"].(string)
				} else {
					name, _ = good["name"].(string)
				}
				if req.Name != nil {
					if *req.Name != name {
						continue
					}
				}
			}

			fc, _ := good["amount"].(float64)
			ic := int64(fc)
			count += ic

			ft, _ := good["totalPrice"].(float64)
			total += ft
		}
	}

	resp.Status = common.SuccessCode
	resp.Message = common.SuccessMessage
	resp.Count = count
	resp.Total = total
	return resp
}
